package com.rybbaby.tss.front.tssPayment.controller;

import com.google.common.collect.ImmutableMap;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rybbaby.tss.core.annotation.RequestLog;
import com.rybbaby.tss.core.annotation.Token;
import com.rybbaby.tss.core.annotation.validator.RegexpValidator;
import com.rybbaby.tss.core.annotation.validator.StringValidator;
import com.rybbaby.tss.core.bean.PageBean;
import com.rybbaby.tss.core.consts.RoleConsts;
import com.rybbaby.tss.core.enums.MemberPropertyEnum;
import com.rybbaby.tss.core.enums.ReceiptTypeEnum;
import com.rybbaby.tss.core.hqlsearch.HqlGenerateUtil;
import com.rybbaby.tss.core.utils.*;
import com.rybbaby.tss.core.web.controller.BaseController;
import com.rybbaby.tss.front.tssAllocation.entity.TssAllocation;
import com.rybbaby.tss.front.tssAllocation.service.ITssAllocationService;
import com.rybbaby.tss.front.tssMealFee.entity.TssMealFee;
import com.rybbaby.tss.front.tssMealFee.service.ITssMealFeeService;
import com.rybbaby.tss.front.tssMemberPackage.entity.TssMemberPackage;
import com.rybbaby.tss.front.tssMemberPackage.service.ITssMemberPackageService;
import com.rybbaby.tss.front.tssMemberReturnPremium.entity.ViewRefundDetails;
import com.rybbaby.tss.front.tssMemberReturnPremium.service.IViewRefundDetailsService;
import com.rybbaby.tss.front.tssMemberTurnHistoryRecord.service.ITssMemberTurnHistoryRecordService;
import com.rybbaby.tss.front.tssPayment.entity.*;
import com.rybbaby.tss.front.tssPayment.service.ITssPaymentService;
import com.rybbaby.tss.front.tssPayment.service.IViewPaymentDetailsService;
import com.rybbaby.tss.front.tssPayment.service.IViewPaymentReturnPremiumService;
import com.rybbaby.tss.front.tssPayment.service.IViewPaymentStudentPackageService;
import com.rybbaby.tss.front.tssPaymentHistory.service.ITssPaymentHistoryService;
import com.rybbaby.tss.front.tssRightStatistic.service.ITssRightStatisticService;
import com.rybbaby.tss.front.tssStudent.entity.TssStudent;
import com.rybbaby.tss.front.tssStudent.entity.ViewStudentDetails;
import com.rybbaby.tss.front.tssStudent.service.ITssStudentService;
import com.rybbaby.tss.front.tssStudent.service.IViewStudentDetailsService;
import com.rybbaby.tss.platform.sysAdminUser.entity.SysAdminUser;
import com.rybbaby.tss.platform.sysAdminUser.service.ISysAdminUserService;
import org.apache.commons.collections.map.HashedMap;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description 缴费表管理
 * 
 * @author 雷春琼
 * 
 * @createDate 2017-08-10 上午12:22:55
 */
@Controller
@RequestMapping(value = "tssPaymentController")
public class TssPaymentController extends BaseController {
	
	@Autowired
	private ITssPaymentService tssPaymentService;
	@Autowired
	private ITssMemberPackageService tssMemberPackageService;
	@Autowired
	private ITssStudentService tssStudentService;
	@Autowired
	private ITssAllocationService tssAllocationService;
	@Autowired
	private IViewPaymentDetailsService viewPaymentDetailsService;
	@Autowired
	private ITssMealFeeService tssMealFeeService;
	@Autowired
	private IViewRefundDetailsService viewRefundDetailsService;
	@Autowired
	private IViewStudentDetailsService viewStudentDetailsService;
	@Autowired
	private ITssPaymentHistoryService tssPaymentHistoryService;
	@Autowired
	private IViewPaymentReturnPremiumService iViewPaymentReturnPremiumService;

	@Autowired
	IViewPaymentStudentPackageService iViewPaymentStudentPackageService;
	@Autowired
	private ITssRightStatisticService tssRightStatisticService;
	@Autowired
	private ISysAdminUserService sysAdminUserService;


	/**
	 * 获取缴费表列表
	 * luowo
	 * @return
	 * @throws IOException
	 */
	@RequestLog(content = "获取缴费表列表" , save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "tssPaymentList" , method = RequestMethod.POST)
	public ModelAndView tssPaymentList(ViewPaymentStudentPackage entity , PageBean paramPageBean) {
		ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssPaymentListView"));
		try {
			Map<String , String []> unLockMap = getParameterMap(request);
			DetachedCriteria dc = DetachedCriteria.forClass(ViewPaymentStudentPackage.class);
			HqlGenerateUtil.fillDetachedCriteria(dc , entity , unLockMap);
			PageBean pageBean = tssPaymentService.pageList(dc , paramPageBean.getPageNo() , paramPageBean.getPageSize());
			mav.addObject("packageType" , entity.getPackageType());
			mav.addObject("paymentApplyStatus" , entity.getPaymentApplyStatus());
			mav.addObject(super.SEARCH_MAP , unLockMap);
			mav.addObject(super.PAGE_BEAN , pageBean);
			mav.addObject("searchFormId" , SEARCH_FORM);
			mav.addObject("actionUrl" , request.getRequestURI());
			mav.addObject("pagingBar" , pageBean.getPagingBar(SEARCH_FORM));
			mav.addObject("serializeNum" , SequenceUtil.getUpperCaseUUID());
			String requestURI = StringUtils.substringBeforeLast(request.getRequestURI() , "/");
			mav.addObject("editUrl" , requestURI + "/toEditView.do");
			mav.addObject("deleteUrl" , requestURI + "/delete.do");
			mav.addObject("batchDeleteUrl" , requestURI + "/batchDelete.do");
		} catch (Exception e) {
			throw e;
		}
		return mav;
	}

	/**
	 * 获取收支管理列表
	 *
	 * @return
	 * @throws IOException
	 */
	@RequestLog(content = "获取收支管理列表" , save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "RevenueExpenditureManagement" , method = RequestMethod.POST)
	public ModelAndView RevenueExpenditureManagement(ViewPaymentReturnPremium entity , PageBean paramPageBean) {
		ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("ViewPaymentReturnPremiumView"));
		try {
			Map<String , String []> unLockMap = getParameterMap(request);
			DetachedCriteria dc = DetachedCriteria.forClass(ViewPaymentReturnPremium.class);
			//获取当前登录者
			String adminUserId = super.getLoginUser().getId();
			SysAdminUser user = super.getLoginUser();
			String ids = "";
			SysAdminUser sysAdminUser=this.sysAdminUserService.get(adminUserId);
			//获取当前登录者所拥有角色
			List<String> roleList = super.getLoginAdminRoles();

            if(roleList.contains(RoleConsts.TSS_COUNSELOR)||roleList.contains(RoleConsts.TSS_TEACHER)){
                dc.add(Restrictions.sqlRestriction(" adminUserId in ('" + adminUserId + "') "));
            } else{
                List<String> idsList = super.getUserIdByRoleAndSchololId(sysAdminUser.getSchoolId());
                ids = StringUtils.join(idsList, "','");
                dc.add(Restrictions.sqlRestriction(" adminUserId in ('" + ids + "') "));
            }
			HqlGenerateUtil.fillDetachedCriteria(dc , entity , unLockMap);
			PageBean pageBean = tssPaymentService.pageList(dc , paramPageBean.getPageNo() , paramPageBean.getPageSize());
			mav.addObject(super.SEARCH_MAP , unLockMap);
			mav.addObject(super.PAGE_BEAN , pageBean);
			mav.addObject("searchFormId" , SEARCH_FORM);
			mav.addObject("actionUrl" , request.getRequestURI());
			mav.addObject("pagingBar" , pageBean.getPagingBar(SEARCH_FORM));
			mav.addObject("serializeNum" , SequenceUtil.getUpperCaseUUID());
			String requestURI = StringUtils.substringBeforeLast(request.getRequestURI() , "/");
			mav.addObject("addUrl" , requestURI + "/toAddedPaymentView.do");
			mav.addObject("editUrl" , requestURI + "/toEditView.do");
			mav.addObject("deleteUrl" , requestURI + "/delete.do");
			mav.addObject("batchDeleteUrl" , requestURI + "/batchDelete.do");
		} catch (Exception e) {
			throw e;
		}
		return mav;
	}
	/**
	 * 获取收支管理列表
	 *
	 * @return
	 * @throws IOException
	 */
	@RequestLog(content = "获取收支管理列表" , save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "ViewPaymentRefundTurnoverList" , method = RequestMethod.POST)
	public ModelAndView ViewPaymentRefundTurnoverList(ViewPaymentRefundTurnover entity , PageBean paramPageBean) {
		ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("ViewPaymentRefundTurnoverListView"));
		try {
			Map<String , String []> unLockMap = getParameterMap(request);
			DetachedCriteria dc = DetachedCriteria.forClass(ViewPaymentRefundTurnover.class);
			HqlGenerateUtil.fillDetachedCriteria(dc , entity , unLockMap);
			//获取当前登录者
			String adminUserId = super.getLoginUser().getId();
			SysAdminUser user = super.getLoginUser();
			String ids = "";
			SysAdminUser sysAdminUser=this.sysAdminUserService.get(adminUserId);
			//获取当前登录者所拥有角色
			List<String> roleList = super.getLoginAdminRoles();

			if(roleList.contains(RoleConsts.TSS_COUNSELOR)||roleList.contains(RoleConsts.TSS_TEACHER)){
				dc.add(Restrictions.sqlRestriction(" aadminUserId in ('" + adminUserId + "') "));
				dc.add(Restrictions.sqlRestriction(" badminUserId in ('" + adminUserId + "') "));
			} else{
				List<String> idsList = super.getUserIdByRoleAndSchololId(sysAdminUser.getSchoolId());
				ids = StringUtils.join(idsList, "','");
				dc.add(Restrictions.sqlRestriction(" aadminUserId in ('" + ids + "') "));
				dc.add(Restrictions.sqlRestriction(" badminUserId in ('" + ids + "') "));
			}
			PageBean pageBean = tssPaymentService.pageList(dc , paramPageBean.getPageNo() , paramPageBean.getPageSize());
			mav.addObject(super.SEARCH_MAP , unLockMap);
			mav.addObject(super.PAGE_BEAN , pageBean);
			mav.addObject("searchFormId" , SEARCH_FORM);
			mav.addObject("actionUrl" , request.getRequestURI());
			mav.addObject("pagingBar" , pageBean.getPagingBar(SEARCH_FORM));
			mav.addObject("serializeNum" , SequenceUtil.getUpperCaseUUID());
			String requestURI = StringUtils.substringBeforeLast(request.getRequestURI() , "/");
			mav.addObject("addUrl" , requestURI + "/toAddedPaymentView.do");
			mav.addObject("editUrl" , requestURI + "/toEditView.do");
			mav.addObject("deleteUrl" , requestURI + "/delete.do");
			mav.addObject("batchDeleteUrl" , requestURI + "/batchDelete.do");
		} catch (Exception e) {
			throw e;
		}
		return mav;
	}
	/**
	 * 收支记录-缴费记录
	 *
	 * @return
	 * @throws IOException
	 */
	@RequestLog(content = "收支记录-缴费记录" , save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "ViewPaymentDetailsList" , method = RequestMethod.POST)
	public ModelAndView ViewPaymentDetailsList(ViewPaymentDetails entity , PageBean paramPageBean) {
		ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("ViewPaymentDetailsListView"));
		try {
			Map<String , String []> unLockMap = getParameterMap(request);
			DetachedCriteria dc = DetachedCriteria.forClass(ViewPaymentDetails.class);
			//获取当前登录者
			String adminUserId = super.getLoginUser().getId();
			SysAdminUser user = super.getLoginUser();
			String ids = "";
			SysAdminUser sysAdminUser=this.sysAdminUserService.get(adminUserId);
			//获取当前登录者所拥有角色
			List<String> roleList = super.getLoginAdminRoles();

			if(roleList.contains(RoleConsts.TSS_COUNSELOR)||roleList.contains(RoleConsts.TSS_TEACHER)){
				dc.add(Restrictions.sqlRestriction(" adminUserId in ('" + adminUserId + "') "));
			} else{
				List<String> idsList = super.getUserIdByRoleAndSchololId(sysAdminUser.getSchoolId());
				ids = StringUtils.join(idsList, "','");
				dc.add(Restrictions.sqlRestriction(" adminUserId in ('" + ids + "') "));
			}
			HqlGenerateUtil.fillDetachedCriteria(dc , entity , unLockMap);
			PageBean pageBean = tssPaymentService.pageList(dc , paramPageBean.getPageNo() , paramPageBean.getPageSize());
			mav.addObject(super.SEARCH_MAP , unLockMap);
			mav.addObject(super.PAGE_BEAN , pageBean);
			mav.addObject("searchFormId" , SEARCH_FORM);
			mav.addObject("actionUrl" , request.getRequestURI());
			mav.addObject("pagingBar" , pageBean.getPagingBar(SEARCH_FORM));
			mav.addObject("serializeNum" , SequenceUtil.getUpperCaseUUID());
			String requestURI = StringUtils.substringBeforeLast(request.getRequestURI() , "/");
			mav.addObject("addUrl" , requestURI + "/toAddedPaymentView.do");
			mav.addObject("editUrl" , requestURI + "/toEditView.do");
			mav.addObject("deleteUrl" , requestURI + "/delete.do");
			mav.addObject("batchDeleteUrl" , requestURI + "/batchDelete.do");
		} catch (Exception e) {
			throw e;
		}
		return mav;
	}
	@RequestLog(content = "转到缴费表视图" , save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "toAddedPaymentView" , method = RequestMethod.GET)
	public ModelAndView toAddedPaymentView(TssPayment entity ,@RequestParam(required = false) String flag, @RequestParam(required = false) String serializeNum, @RequestParam(required = false) String targetdataid
			, @RequestParam(required = false) String user,@RequestParam(required = false) String other) {
		ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("toDepositPaymentView"));
		try {
			if(flag != null && !"".equals(flag)){
				if("1".equals(flag)) {
					mav.setViewName(PropertiesReadUtil.getStringProperty("toDepositPaymentView"));
				}
				if("2".equals(flag)) {
					if(user != null && !"".equals(user)){

					}else {
						List<TssPayment> paymentList = this.tssPaymentService.findDepositById(targetdataid);
						if(paymentList.size()>0){
							double sumDeposit = 0;
							String depositIds = "";
							for (int i = 0; i < paymentList.size(); i++){
								sumDeposit = sumDeposit + paymentList.get(i).getAmount();
								if(i == 0){
									depositIds = depositIds + paymentList.get(i).getId();
								}else{
									depositIds = depositIds + "," + paymentList.get(i).getId();
								}
							}
							mav.addObject("deposit", sumDeposit);
							mav.addObject("depositIds", depositIds);
						}
					}
						mav.setViewName(PropertiesReadUtil.getStringProperty("toPackagePaymentView"));
					}
				if("3".equals(flag)) {
					if(user != null && "".equals(user)){

					}else {
						List<TssMealFee> destEntity = this.tssMealFeeService.findByProperty("stuId",targetdataid);
						if(destEntity.size()>0){
							Double dayMealFee = destEntity.get(0).getDayMealFee();
							mav.addObject("dayMealFee", dayMealFee);
						}
					}
					mav.setViewName(PropertiesReadUtil.getStringProperty("toOtherPaymentView"));
				}
			}
			if(targetdataid!=null && !"".equals(targetdataid)){
				Map<String, Object> studentDetailById = tssStudentService.getStudentDetailById(targetdataid);
				//TssStudent student=tssStudentService.get(targetdataid);
				mav.addObject("empAdminUserId", studentDetailById.get("empAdminUserId"));
			}
			mav.addObject("other", other);
			mav.addObject("user", user);
			mav.addObject("flag" , flag);
			mav.addObject("serializeNum" , serializeNum);
			mav.addObject("targetdataid" , targetdataid);
			mav.addObject("saveUrl" , StringUtils.substringBeforeLast(request.getRequestURI() , "/") + "/saveOrUpdate.do");
		} catch (Exception e) {
			//throw e;
			e.printStackTrace();
		}
		return mav;
	}
	/**
	 * 获取费用详情
	 *
	 * @return
	 * @throws IOException
	 */
	@RequestLog(content = "获取费用详情", save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "chargeDetails", method = RequestMethod.GET)
	public ModelAndView chargeDetails(ViewPaymentDetails entity) {
		ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("ViewChargeDetailsView"));
		try {
			mav.addObject("stuId" , entity.getStuId());
			//用户信息
			ViewStudentDetails viewStudentDetails = viewStudentDetailsService.get(entity.getStuId());
			mav.addObject("viewStudentDetails" , viewStudentDetails);
			//缴费详情
			List<ViewPaymentDetails> packageDetailsList = this.viewPaymentDetailsService.packageDetailsList(entity.getStuId());
			List<ViewPaymentDetails> DepositDetailsList = this.viewPaymentDetailsService.DepositDetailsList(entity.getStuId());
			List<ViewPaymentDetails> otherPaymentDetailsList = this.viewPaymentDetailsService.otherPaymentDetailsList(entity.getStuId());
			//退费详情
			List<ViewRefundDetails> viewRefundDetailsList = viewRefundDetailsService.viewRefundDetailsList(entity.getStuId());
			//前台序号
			int index = 0;
			for (int j = 0; j < packageDetailsList.size(); j++) {
				ViewPaymentDetails paymentDetails = packageDetailsList.get(j);
				if (paymentDetails.getPaymentType() == 3) {
					List<ViewPaymentDetails> packagePaymentDetailsList = this.viewPaymentDetailsService.packagePaymentDetails(paymentDetails.getPackageId());
					paymentDetails.setPackageDetailsList(packagePaymentDetailsList);
				}
				index++;
				paymentDetails.setIndex(index);
			}
			for (int j = 0; j < DepositDetailsList.size(); j++) {
				ViewPaymentDetails paymentDetails = DepositDetailsList.get(j);
				index++;
				paymentDetails.setIndex(index);
			}
			for (int j = 0; j < otherPaymentDetailsList.size(); j++) {
				ViewPaymentDetails paymentDetails = otherPaymentDetailsList.get(j);
				index++;
				paymentDetails.setIndex(index);
			}
			for (int j = 0; j < viewRefundDetailsList.size(); j++) {
				ViewRefundDetails viewRefundDetails = viewRefundDetailsList.get(j);
				index++;
				viewRefundDetails.setIndex(index);
			}


			mav.addObject("packageDetailsList", packageDetailsList);
			mav.addObject("DepositDetailsList", DepositDetailsList);
			mav.addObject("otherPaymentDetailsList", otherPaymentDetailsList);
			mav.addObject("viewRefundDetailsList" , viewRefundDetailsList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}
	/**
	 * 获取会员缴费详情
	 *
	 * @return
	 * @throws IOException
	 */
	@RequestLog(content = "获取会员缴费详情", save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "ViewPaymentDetails", method = RequestMethod.GET)
	public ModelAndView ViewPaymentDetails(ViewPaymentDetails entity) {
		ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("ViewPaymentDetailsView"));
		try {
			mav.addObject("stuId" , entity.getStuId());
			//用户信息
			ViewStudentDetails viewStudentDetails = viewStudentDetailsService.get(entity.getStuId());
			mav.addObject("viewStudentDetails" , viewStudentDetails);
			Map<String, Object> map = this.viewPaymentDetailsService.getPaymentListByMemberId(entity);
			mav.addObject("packageDetailsList", map.get("packageDetailsList"));
			mav.addObject("DepositDetailsList", map.get("DepositDetailsList"));
			mav.addObject("otherPaymentDetailsList", map.get("otherPaymentDetailsList"));

		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}
	/**
	 * 查询课时包关联的缴费详情
	 *
	 * @param entity
	 *            被编辑对象
	 * @return
	 */
	@ResponseBody
	@RequestLog(content = "查询课时包关联的缴费详情" , save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "packagePaymentDetails" , method = RequestMethod.GET)
	public String packagePaymentDetails(ViewPaymentDetails entity) {
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		try {
			List<ViewPaymentDetails> packagePaymentDetailsList = this.viewPaymentDetailsService.packagePaymentDetails(entity.getPackageId());
			ajr.setData(packagePaymentDetailsList);
		} catch (Exception e) {
			//throw e;
			e.printStackTrace();
		}
		return ajr.jsonResponse(true);
	}
	/**
	 * 转到编辑视图
	 *
	 * @param entity
	 *            接收编辑参数的临时对象
	 * @param serializeNum
	 *            请求标识
	 * @return
	 */
	@RequestLog(content = "转到缴费表视图" , save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "toEditView" , method = RequestMethod.GET)
	public ModelAndView toEditView(TssPayment entity , @RequestParam(required = true) String serializeNum) {
		ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssPaymentEditView"));
		if(entity != null && entity.getId() != null) {
			TssPayment editEntity = this.tssPaymentService.get(entity.getId());
			mav.addObject("editEntity" , editEntity);
			mav.addObject("editModel" , "edit");
		}else{
			mav.addObject("editModel" , "add");
		}
		mav.addObject("serializeNum" , serializeNum);
		mav.addObject("saveUrl" , StringUtils.substringBeforeLast(request.getRequestURI() , "/") + "/saveOrUpdate.do");
		return mav;
	}
	/**
	 * 查询用户定金
	 *
	 * @param entity
	 *            被编辑对象
	 * @return
	 */
	@ResponseBody
	@RequestLog(content = "查询用户定金" , save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "findDepositById" , method = RequestMethod.GET)
	public String findDepositById(TssPayment entity) {
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		try {
			//List<TssPayment> payment=this.tssStudentService.findStudentByName(entity.getName());
			List<TssPayment> paymentList = this.tssPaymentService.findDepositById(entity.getId());
			double sumDeposit = 0;
			String depositIds = "";
			for (int i = 0; i < paymentList.size(); i++){
				sumDeposit += paymentList.get(i).getAmount();
				if(i == 0){
					depositIds = depositIds;
				}else{
					depositIds = depositIds + "," + paymentList.get(i).getId();
				}
			}
			ajr.setData(sumDeposit);
			ajr.setData(depositIds);
		} catch (Exception e) {
			//throw e;
			e.printStackTrace();
		}
		return ajr.jsonResponse(true);
	}
	/**
	 * 查询合同编号
	 *
	 * @param entity
	 *            被编辑对象
	 * @return
	 */
	@ResponseBody
	@RequestLog(content = "查询合同编号" , save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "ajaxContractNumber" , method = RequestMethod.GET)
	public String ajaxContractNumber(TssPayment entity) {
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		try {
			ajr.setResMsg("合同编号已存在!");
			Map<String,Object> map= this.tssPaymentService.findContractNumber(entity.getContractNumber());
			if("0".equals(map.get("size").toString())){
				ajr.setResMsg("合同编号可使用!");
			}
		} catch (Exception e) {
			//throw e;
			e.printStackTrace();
		}
		return ajr.jsonResponse(true);
	}
	/*@ResponseBody
	@RequestLog(content = "保存缴费表对象" , save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "saveOrUpdate" , method = RequestMethod.POST)
	public String saveOrUpdate(TssPayment entity) {
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		String adminUserId = super.getLoginUser().getId();
		try {
			TssPayment payment = new TssPayment();
			String paymentType = request.getParameter("paymentType");
			ajr.setResMsg("保存成功!");
			String uuid = UUID.randomUUID().toString();
			if(StringUtils.isNotBlank(paymentType)){
				String depositAmount = request.getParameter("depositAmount");
				String depositRemark = request.getParameter("depositRemark");
				//保存定金
				payment.setId(uuid);
				payment.setAdminUserId(adminUserId);
				payment.setAmount( Double.parseDouble(depositAmount));
				payment.setPaymentType(Integer.parseInt(paymentType));
				payment.setDepositStatus(1);
				payment.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
				this.tssPaymentService.save(payment);
			} else {

			}
		} catch (Exception e) {
			e.printStackTrace();
			ajr.setResCode(500);
			ajr.setResMsg("保存失败(" + e.getMessage() + ")!");
		}
		return ajr.jsonResponse(false);
	}*/
	/**
	 * 保存编辑的对象
	 * 
	 * @param entity
	 *            被编辑对象
	 * @return
	 */
	@ResponseBody
	@RequestLog(content = "保存缴费表对象" , save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "saveOrUpdate" , method = RequestMethod.POST)
	public String saveOrUpdate(TssPayment entity,TssMemberPackage packageEntity,@RequestParam(required = false) String flag
			) {
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		String adminUserId = super.getLoginUser().getId();
		Map<String, Object> schoolCode = sysAdminUserService.findSchoolCode(adminUserId);
		try {
			/*TssPayment payment = new TssPayment();
			String paymentType = request.getParameter("paymentType");*/
			ajr.setResMsg("保存成功!");
			//if(StringUtils.isNotBlank(entity)){
			//客户购买课时包时stuId
			String targetdataid = request.getParameter("targetdataid");
			//新增缴费stuId
			String stuId = request.getParameter("stuId");
			String studentId= "";
			if(targetdataid != null){
				studentId = targetdataid;
			}else{
				studentId = stuId;
			}
			Serializable historyId = "";
			if("1".equals(flag)){
				//生成缴费编码
				Map<String, Object> paramsMap = new HashMap<>();
				paramsMap.put("sequenceName", "SEQUENCE_TSS_PAYMEMT_CODE");
				paramsMap.put("schoolCode",schoolCode.get("schoolCode"));
				paramsMap.put("receiptType", ReceiptTypeEnum.缴费.value());
				String resultCode = CodeGenUtil.getCodeGen(paramsMap);
				Gson gson = new Gson();
				Map<String,Object> map = gson.fromJson(resultCode, new TypeToken<Map<String,Object>>() {
				}.getType());
				if(Double.parseDouble(map.get("resCode")+"")==200){
					entity.setPaymentCode(map.get("data").toString());
				}
				//保存定金
				entity.setStuId(studentId);
				entity.setEmpAdminUserId(packageEntity.getEmpAdminUserId());
				entity.setAdminUserId(adminUserId);
				entity.setDepositStatus(1);
				entity.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
				entity.setUpdateTime(new java.sql.Timestamp(System.currentTimeMillis()));
				Serializable depositId = tssPaymentService.saveEntity(entity);
				historyId = tssPaymentHistoryService.saveHistory(entity);
				if (depositId == null) {
					ajr.setResCode(301);
					ajr.setResMsg("保存订金缴费信息失败!");
				}
				if (historyId == null) {
					ajr.setResCode(301);
					ajr.setResMsg("保存操作历史信息失败!");
				}

				this.tssStudentService.updateParameterById(ImmutableMap.of("stuStatus",4),studentId);
				List<TssAllocation> tssAllocations = tssAllocationService.findByEmpAdminUserId(packageEntity.getEmpAdminUserId(),studentId);
				if(tssAllocations.size()<1){
					TssAllocation tssAllocation = new TssAllocation();
					tssAllocation.setStudentId(entity.getStuId());
					tssAllocation.setEmpAdminUserId(packageEntity.getEmpAdminUserId());
					tssAllocation.setAdminUserId(adminUserId);
					tssAllocation.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
					Serializable save = tssAllocationService.save(tssAllocation);
				}
				this.tssStudentService.updateParameterById(ImmutableMap.of("empAdminUserId",packageEntity.getEmpAdminUserId()),studentId);
			}
			if("2".equals(flag)){
				//保存课时包
				ajr.setResMsg("保存成功!");
				TssMemberPackage tssMemberPackage = new TssMemberPackage();
				TssMemberPackage saveMemberPackage = new TssMemberPackage();
				String type = request.getParameter("packageType");

				String depositIds = request.getParameter("depositIds");
				TssPayment packagePayment = new TssPayment();

				if("1".equals(type)){
					//所属顾问
					String dearSonStaffId = request.getParameter("dearSonStaffId");
					entity.setEmpAdminUserId(dearSonStaffId);
					String dearSonPackageId = request.getParameter("dearSonPackageId");
					//课时
					Integer classHour = Integer.parseInt("".equals(request.getParameter("classHour"))?"0":request.getParameter("classHour"));
					//赠送课时
					Integer dearSonPresentClassHour = Integer.parseInt("".equals(request.getParameter("dearSonPresentClassHour"))?"0":request.getParameter("dearSonPresentClassHour"));
					//折后单价
					Double dearSonNowUnitPrice = Double.valueOf("".equals(request.getParameter("dearSonNowUnitPrice"))?"0.00":request.getParameter("dearSonNowUnitPrice"));
					//有效期
					Integer dearSonValidDate = Integer.parseInt("".equals(request.getParameter("dearSonValidDate"))?"0.":request.getParameter("dearSonValidDate"));
					//已缴纳定金
					Double dearSonDeposit = Double.valueOf("".equals(request.getParameter("dearSonDeposit"))?"0.00":request.getParameter("dearSonDeposit"));
					//课时包总价
					Double dearSonPackageSumPrice = Double.valueOf("".equals(request.getParameter("dearSonPackageSumPrice"))?"0.00":request.getParameter("dearSonPackageSumPrice"));
					//课时包折后总价
					Double dearSonPackageDiscountSumPrice = Double.valueOf("".equals(request.getParameter("dearSonPackageDiscountSumPrice"))?"0.00":request.getParameter("dearSonPackageDiscountSumPrice"));
					//应支付总额
					Double dearSonShouldPayPackagePrice = Double.valueOf("".equals(request.getParameter("dearSonShouldPayPackagePrice"))?"0.00":request.getParameter("dearSonShouldPayPackagePrice"));
					//备注
					String dearSonRemark = request.getParameter("dearSonRemark");
					//可用课时数
					Integer usableTotalClassHour = Integer.parseInt("".equals(request.getParameter("usableTotalClassHour"))?"0":request.getParameter("usableTotalClassHour"));
					//试听老师
					String dearSonTeacherId = request.getParameter("dearSonTeacherId");
					//赠品价值
					Double dearSonGifts = Double.valueOf("".equals(request.getParameter("dearSonGifts"))?"0.00":request.getParameter("dearSonGifts"));
					//报名费
					Double dearSonRegisteryFee = Double.valueOf("".equals(request.getParameter("dearSonRegisteryFee"))?"0.00":request.getParameter("dearSonRegisteryFee"));

					//重新计算
					//课时包补缴（扣除订金）金额
					BigDecimal dearSonPackageDiscountSumPriceBig = new BigDecimal(dearSonPackageDiscountSumPrice.toString());
					Double packagePaymentAmount = dearSonPackageDiscountSumPriceBig.subtract(new BigDecimal(dearSonDeposit.toString())).setScale(2, BigDecimal.ROUND_UP).doubleValue();
					//可用课时数
					usableTotalClassHour = classHour+dearSonPresentClassHour;
					//折后单价
					dearSonNowUnitPrice = dearSonPackageDiscountSumPriceBig.divide(new BigDecimal(classHour.toString()),2,BigDecimal.ROUND_UP).setScale(2, BigDecimal.ROUND_UP).doubleValue();
					//优惠金额
					BigDecimal dearSonPackageSumPriceBig = new BigDecimal(dearSonPackageSumPrice.toString());
					Double discountedPrice = dearSonPackageSumPriceBig.subtract(new BigDecimal(dearSonPackageDiscountSumPrice.toString())).setScale(2, BigDecimal.ROUND_UP).doubleValue();


					tssMemberPackage.setMemberId(studentId);
					tssMemberPackage.setAdminUserId(adminUserId);
					tssMemberPackage.setContractNumber(packageEntity.getContractNumber());
					tssMemberPackage.setType(Integer.parseInt(type));
					tssMemberPackage.setEmpAdminUserId(dearSonStaffId);
					tssMemberPackage.setPackageId(dearSonPackageId);
					tssMemberPackage.setPresentClassHour(dearSonPresentClassHour);
					tssMemberPackage.setGifts(dearSonGifts);
					tssMemberPackage.setTeacherId(dearSonTeacherId);


					tssMemberPackage.setDiscountedPrice(discountedPrice);
					tssMemberPackage.setNowUnitPrice(dearSonNowUnitPrice);
					tssMemberPackage.setSurplusValidDate(dearSonValidDate);
					tssMemberPackage.setSumPrice(dearSonPackageDiscountSumPrice);
					tssMemberPackage.setRemark(dearSonRemark);
					tssMemberPackage.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
					tssMemberPackage.setUpdateTime(new java.sql.Timestamp(System.currentTimeMillis()));

					tssMemberPackage.setUsableTotalClassHour(usableTotalClassHour);
					tssMemberPackage.setSurplusClassHour(usableTotalClassHour);
					tssMemberPackage.setSurplusFormalClassHour(classHour);
					tssMemberPackage.setSurplusPresentClassHour(dearSonPresentClassHour);
					tssMemberPackage.setPackageStatus(2);

					BeanUtils.copyProperties(tssMemberPackage, saveMemberPackage);

					//缴费金额
					packagePayment.setAmount(packagePaymentAmount);
					//保存报名费
					if(dearSonRegisteryFee !=0.00) {
						TssPayment dearSonRegisteryFeePayment = new TssPayment();
						//生成缴费编码
						Map<String, Object> paramsMap = new HashMap<>();
						paramsMap.put("sequenceName", "SEQUENCE_TSS_PAYMEMT_CODE");
						paramsMap.put("schoolCode",schoolCode.get("schoolCode"));
						paramsMap.put("receiptType", ReceiptTypeEnum.缴费.value());
						String resultCode = CodeGenUtil.getCodeGen(paramsMap);
						Gson gson = new Gson();
						Map<String,Object> map = gson.fromJson(resultCode, new TypeToken<Map<String,Object>>() {
						}.getType());
						if(Double.parseDouble(map.get("resCode")+"")==200){
							dearSonRegisteryFeePayment.setPaymentCode(map.get("data").toString());
						}
						dearSonRegisteryFeePayment.setStuId(studentId);
						dearSonRegisteryFeePayment.setAdminUserId(adminUserId);
						dearSonRegisteryFeePayment.setAmount(dearSonRegisteryFee);
						dearSonRegisteryFeePayment.setContractNumber(tssMemberPackage.getContractNumber());
						dearSonRegisteryFeePayment.setPaymentType(7);
						dearSonRegisteryFeePayment.setRemark(tssMemberPackage.getRemark());
						dearSonRegisteryFeePayment.setEmpAdminUserId(entity.getEmpAdminUserId());
						dearSonRegisteryFeePayment.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
						dearSonRegisteryFeePayment.setUpdateTime(new java.sql.Timestamp(System.currentTimeMillis()));
						Serializable disposableItemsnewId = this.tssPaymentService.saveEntity(dearSonRegisteryFeePayment);
						if (disposableItemsnewId == null) {
							ajr.setResCode(301);
							ajr.setResMsg("保存报名费失败!");
						}
						//缴费记录
						TssPayment tssPayment = tssPaymentService.get(disposableItemsnewId);
						historyId = tssPaymentHistoryService.saveHistory(tssPayment);
						if (historyId == null) {
							ajr.setResCode(301);
							ajr.setResMsg("保存操作历史信息失败!");
						}
					}
				}else{
					String empAdminUserId = request.getParameter("adminUserId");
					String isComplimentaryMeals = request.getParameter("isComplimentaryMeals");
					entity.setEmpAdminUserId(empAdminUserId);
					//出勤天数
					Integer packageAttendanceDay = Integer.parseInt("".equals(request.getParameter("packageAttendanceDay"))?"0":request.getParameter("packageAttendanceDay"));
					//赠送天数
					Integer transitionGiftAttendanceDay = Integer.parseInt("".equals(request.getParameter("transitionGiftAttendanceDay"))?"0":request.getParameter("transitionGiftAttendanceDay"));
					//课时包总价
					Double packageSumPrice = Double.valueOf("".equals(request.getParameter("packageSumPrice"))?"0.00":request.getParameter("packageSumPrice"));
					//课时包折后总价
					Double packageDiscountSumPrice = Double.valueOf("".equals(request.getParameter("packageDiscountSumPrice"))?"0.00":request.getParameter("packageDiscountSumPrice"));
					//一次性物品费
					Double disposableItems = Double.valueOf("".equals(request.getParameter("disposableItems"))?"0.00":request.getParameter("disposableItems"));
					//日餐点费
					Double dayMealFee = Double.valueOf("".equals(request.getParameter("dayMealFee"))?"0.00":request.getParameter("dayMealFee"));
					//餐点费总计
					Double totalMealFee = Double.valueOf("".equals(request.getParameter("totalMealFee"))?"0.00":request.getParameter("totalMealFee"));
					//已缴纳定金
					Double deposit = Double.valueOf("".equals(request.getParameter("deposit"))?"0.00":request.getParameter("deposit"));
					//可出勤天数
					Integer attendanceDay = Integer.parseInt("".equals(request.getParameter("attendanceDay"))?"0":request.getParameter("attendanceDay"));


					//重新计算
					//课时包补缴（扣除订金）金额
					BigDecimal packageDiscountSumPriceBig = new BigDecimal(packageDiscountSumPrice.toString());
					Double payAmount = packageDiscountSumPriceBig.subtract(new BigDecimal(deposit.toString())).setScale(2, BigDecimal.ROUND_UP).doubleValue();
					//可用课时数
					attendanceDay = packageAttendanceDay+transitionGiftAttendanceDay;
					//折后单价
					Double nowUnitPrice = packageDiscountSumPriceBig.divide(new BigDecimal(packageAttendanceDay.toString()),2,BigDecimal.ROUND_UP).setScale(2, BigDecimal.ROUND_UP).doubleValue();
					//餐点费
					BigDecimal dayMealFeeBig = new BigDecimal(dayMealFee.toString());
					if(isComplimentaryMeals.equals("1")){
						totalMealFee = dayMealFeeBig.multiply(new BigDecimal(attendanceDay.toString())).setScale(2, BigDecimal.ROUND_UP).doubleValue();
					}
					if(isComplimentaryMeals.equals("2")){
						totalMealFee = dayMealFeeBig.multiply(new BigDecimal(packageAttendanceDay.toString())).setScale(2, BigDecimal.ROUND_UP).doubleValue();
					}


					//优惠金额
					BigDecimal packageSumPriceBig = new BigDecimal(packageSumPrice.toString());
					Double discountedPrice = packageSumPriceBig.subtract(new BigDecimal(packageDiscountSumPrice.toString())).setScale(2, BigDecimal.ROUND_UP).doubleValue();

					packageEntity.setDiscountedPrice(discountedPrice);
					packageEntity.setSumPrice(packageDiscountSumPrice);

					packageEntity.setMemberId(studentId);
					packageEntity.setAdminUserId(adminUserId);
					packageEntity.setEmpAdminUserId(empAdminUserId);
					packageEntity.setType(Integer.parseInt(type));
					packageEntity.setNowUnitPrice(nowUnitPrice);
					packageEntity.setPackageStatus(2);
					packageEntity.setGiftAttendanceDay(transitionGiftAttendanceDay);
					packageEntity.setAttendanceDay(attendanceDay);
					packageEntity.setSurplusAttendanceDay(attendanceDay);
					packageEntity.setSurplusFormalAttendanceDay(packageAttendanceDay);
					packageEntity.setSurplusPresentAttendanceDay(transitionGiftAttendanceDay);

					packageEntity.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
					packageEntity.setUpdateTime(new java.sql.Timestamp(System.currentTimeMillis()));
					BeanUtils.copyProperties(packageEntity, saveMemberPackage);

					//缴费金额
					packagePayment.setAmount(payAmount);

					//保存餐点费缴费信息
					if(totalMealFee!=0.00) {
						TssPayment mealFeePayment = new TssPayment();
						//生成缴费编码
						Map<String, Object> paramsMap = new HashMap<>();
						paramsMap.put("sequenceName", "SEQUENCE_TSS_PAYMEMT_CODE");
						paramsMap.put("schoolCode",schoolCode.get("schoolCode"));
						paramsMap.put("receiptType", ReceiptTypeEnum.缴费.value());
						String resultCode = CodeGenUtil.getCodeGen(paramsMap);
						Gson gson = new Gson();
						Map<String,Object> map = gson.fromJson(resultCode, new TypeToken<Map<String,Object>>() {
						}.getType());
						if(Double.parseDouble(map.get("resCode")+"")==200){
							mealFeePayment.setPaymentCode(map.get("data").toString());
						}
						mealFeePayment.setStuId(studentId);
						mealFeePayment.setAdminUserId(adminUserId);
						mealFeePayment.setEmpAdminUserId(empAdminUserId);
						mealFeePayment.setAmount(totalMealFee);
						mealFeePayment.setContractNumber(packageEntity.getContractNumber());
						mealFeePayment.setPaymentType(4);
						mealFeePayment.setRemark(packageEntity.getRemark());
						mealFeePayment.setEmpAdminUserId(entity.getEmpAdminUserId());
						mealFeePayment.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
						mealFeePayment.setUpdateTime(new java.sql.Timestamp(System.currentTimeMillis()));
						Serializable mealFeenewId = tssPaymentService.saveEntity(mealFeePayment);
						if (mealFeenewId == null) {
							ajr.setResCode(301);
							ajr.setResMsg("保存餐点费缴费信息失败!");
						}
						//缴费记录
						TssPayment tssPayment = tssPaymentService.get(mealFeenewId);
						historyId = tssPaymentHistoryService.saveHistory(tssPayment);
						if (historyId == null) {
							ajr.setResCode(301);
							ajr.setResMsg("保存操作历史信息失败!");
						}

						TssMealFee tssMealFee = new TssMealFee();
						Double amount = totalMealFee;
						List<TssMealFee> destEntity = this.tssMealFeeService.findByProperty("stuId",saveMemberPackage.getMemberId());
						if(destEntity.size() > 0){
							amount = amount + destEntity.get(0).getAmount();
							tssMealFee.setAmount(amount);
							Double surplusAmout = amount + destEntity.get(0).getSurplusAmout();
							tssMealFee.setSurplusAmout(surplusAmout);
							tssMealFee.setUpdateTime(new java.sql.Timestamp(System.currentTimeMillis()));
							BeanUtils.copyProperties(tssMealFee,destEntity.get(0),"id","stuId","dayMealFee","consumptionAmount","createTime");
							this.tssMealFeeService.updateTssMealFee(destEntity.get(0));
						} else {
							tssMealFee.setStuId(saveMemberPackage.getMemberId());
							tssMealFee.setDayMealFee(dayMealFee);
							tssMealFee.setAmount(totalMealFee);
							tssMealFee.setSurplusAmout(totalMealFee);
							tssMealFee.setConsumptionAmount(totalMealFee);
							tssMealFee.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
							tssMealFee.setUpdateTime(new java.sql.Timestamp(System.currentTimeMillis()));

							Serializable tssMealFeenewId = this.tssMealFeeService.saveTssMealFee(tssMealFee);
							if (mealFeenewId == null) {
								ajr.setResCode(301);
								ajr.setResMsg("保存餐点费失败!");
							}
						}



					}
					//保存一次性物品缴费信息
					if(disposableItems !=0.00) {
						TssPayment disposableItemsPayment = new TssPayment();
						//生成缴费编码
						Map<String, Object> paramsMap = new HashMap<>();
						paramsMap.put("sequenceName", "SEQUENCE_TSS_PAYMEMT_CODE");
						paramsMap.put("schoolCode",schoolCode.get("schoolCode"));
						paramsMap.put("receiptType", ReceiptTypeEnum.缴费.value());
						String resultCode = CodeGenUtil.getCodeGen(paramsMap);
						Gson gson = new Gson();
						Map<String,Object> map = gson.fromJson(resultCode, new TypeToken<Map<String,Object>>() {
						}.getType());
						if(Double.parseDouble(map.get("resCode")+"")==200){
							disposableItemsPayment.setPaymentCode(map.get("data").toString());
						}
						disposableItemsPayment.setStuId(studentId);
						disposableItemsPayment.setAdminUserId(adminUserId);
						disposableItemsPayment.setEmpAdminUserId(empAdminUserId);
						disposableItemsPayment.setAmount(disposableItems);
						disposableItemsPayment.setContractNumber(packageEntity.getContractNumber());
						disposableItemsPayment.setPaymentType(5);
						disposableItemsPayment.setRemark(packageEntity.getRemark());
						disposableItemsPayment.setEmpAdminUserId(entity.getEmpAdminUserId());
						disposableItemsPayment.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
						disposableItemsPayment.setUpdateTime(new java.sql.Timestamp(System.currentTimeMillis()));
						Serializable disposableItemsnewId = this.tssPaymentService.saveEntity(disposableItemsPayment);
						if (disposableItemsnewId == null) {
							ajr.setResCode(301);
							ajr.setResMsg("保存一次性物品费失败!");
						}
						//缴费记录
						TssPayment tssPayment = tssPaymentService.get(disposableItemsnewId);
						historyId = tssPaymentHistoryService.saveHistory(tssPayment);
						if (historyId == null) {
							ajr.setResCode(301);
							ajr.setResMsg("保存操作历史信息失败!");
						}

						//一次性物品费权责
						HashMap<String, Object> map1 = new HashMap<>();
						map1.put("memberId", studentId);
						map1.put("paymentId", disposableItemsnewId);
						boolean d = tssRightStatisticService.saveOrUpdateTssRightStatisticService(null,map1,adminUserId,4,8,0,disposableItems);

						if (!d) {
							ajr.setResCode(301);
							ajr.setResMsg("保存一次性物品费权责失败!");
						}

					}
				}
				//设置报名状态
				Map<String,Object> applyStatusMap = tssMemberPackageService.findApplyStatus(saveMemberPackage.getType(),saveMemberPackage.getMemberId());
				if(Integer.parseInt(applyStatusMap.get("size").toString())>0){
					saveMemberPackage.setApplyStatus(1);
				}else{
					saveMemberPackage.setApplyStatus(0);
				}
				//保存会员课时包
				Serializable newPackageId = this.tssMemberPackageService.saveMemberPackage(saveMemberPackage);

				//保存课时包缴费信息
				//生成缴费编码
				Map<String, Object> paramsMap = new HashMap<>();
				paramsMap.put("sequenceName", "SEQUENCE_TSS_PAYMEMT_CODE");
				paramsMap.put("schoolCode",schoolCode.get("schoolCode"));
				paramsMap.put("receiptType", ReceiptTypeEnum.缴费.value());
				String resultCode = CodeGenUtil.getCodeGen(paramsMap);
				Gson gson = new Gson();
				Map<String,Object> map = gson.fromJson(resultCode, new TypeToken<Map<String,Object>>() {
				}.getType());
				if(Double.parseDouble(map.get("resCode")+"")==200){
					packagePayment.setPaymentCode(map.get("data").toString());
				}
				packagePayment.setStuId(studentId);
				packagePayment.setAdminUserId(adminUserId);
				packagePayment.setContractNumber(saveMemberPackage.getContractNumber());
				packagePayment.setPackageId(saveMemberPackage.getId());
				packagePayment.setRemark(saveMemberPackage.getRemark());
				packagePayment.setEmpAdminUserId(entity.getEmpAdminUserId());
				if(depositIds !=null && !"".equals(depositIds)){
					packagePayment.setPaymentType(3);
				}else{
					packagePayment.setPaymentType(1);
				}
				//设置报名状态
				packagePayment.setApplyStatus(saveMemberPackage.getApplyStatus());
				packagePayment.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
				packagePayment.setUpdateTime(new java.sql.Timestamp(System.currentTimeMillis()));
				Serializable packageId = this.tssPaymentService.saveEntity(packagePayment);
				if(packageId == null) {
					ajr.setResCode(301);
					ajr.setResMsg("保存课时包失败!");
				}
				//缴费记录
				TssPayment tssPayment = tssPaymentService.get(packageId);
				historyId = tssPaymentHistoryService.saveHistory(tssPayment);
				if (historyId == null) {
					ajr.setResCode(301);
					ajr.setResMsg("保存操作历史信息失败!");
				}

				//更新订金状态
				SequenceUtil.getUpperCaseUUID();
				if(depositIds !=null && !"".equals(depositIds)){
					String[]  strs = depositIds.split(",");
					int j = this.tssPaymentService.updateDepositIds(strs,saveMemberPackage.getId(),saveMemberPackage.getContractNumber());
				}


				List<TssAllocation> tssAllocations = tssAllocationService.findByEmpAdminUserId(entity.getEmpAdminUserId(),studentId);
				if(tssAllocations.size()<1){
					TssAllocation tssAllocation = new TssAllocation();
					tssAllocation.setStudentId(entity.getStuId());
					tssAllocation.setEmpAdminUserId(entity.getEmpAdminUserId());
					tssAllocation.setAdminUserId(adminUserId);
					tssAllocation.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
					Serializable save = tssAllocationService.save(tssAllocation);
				}
				TssStudent tssStudent = tssStudentService.get(saveMemberPackage.getMemberId());
				if (newPackageId != null) {
					Map<String,Object> map1=new HashedMap();
					//map.put("isMember",true);
					map1.put("adminUserId",saveMemberPackage.getEmpAdminUserId());
					map1.put("empAdminUserId",entity.getEmpAdminUserId());
					map1.put("stuStatus",5);
					if(tssStudent.getIsMember()!=null){
						if(!tssStudent.getIsMember()){
							this.tssStudentService.updateStudentIsMember(studentId);
							//生成会员编码
							Map<String, Object> newParamsMap = new HashMap<>();
							newParamsMap.put("sequenceName", "SEQUENCE_TSS_MEMBER_CODE");
							newParamsMap.put("schoolCode",schoolCode.get("schoolCode"));
							newParamsMap.put("receiptType", MemberPropertyEnum.宝宝.value());
							String newResultCode = CodeGenUtil.getCodeGen(newParamsMap);
							Gson newGson = new Gson();
							Map<String,Object> map2 = newGson.fromJson(newResultCode, new TypeToken<Map<String,Object>>() {
							}.getType());
							String memberCode = "";
							if(Double.parseDouble(map2.get("resCode")+"")==200){
								memberCode = map2.get("data").toString();
								map1.put("memberCode",memberCode);
								map1.put("turnIntoMemberDate",new Timestamp(System.currentTimeMillis()));
							}
						}
					}
					Integer tssStuId = tssStudentService.updateParameterById(map1, saveMemberPackage.getMemberId());
					if (tssStuId<=0) {
						ajr.setResCode(301);
						ajr.setResMsg("更新操作人和转会员时间失败!");
					}
				}


				/*//将客户转会员

				this.tssStudentService.updateParameterById(ImmutableMap.of("stuStatus",5),studentId);
				//更新会员顾问
				this.tssStudentService.updateParameterById(ImmutableMap.of("empAdminUserId",entity.getEmpAdminUserId()),studentId);*/
			}
			if("3".equals(flag)){
				if(studentId != null){
					entity.setStuId(studentId);
				}else{
					entity.setStuId(stuId);
				}
				//生成缴费编码
				Map<String, Object> paramsMap = new HashMap<>();
				paramsMap.put("sequenceName", "SEQUENCE_TSS_PAYMEMT_CODE");
				paramsMap.put("schoolCode",schoolCode.get("schoolCode"));
				paramsMap.put("receiptType", ReceiptTypeEnum.缴费.value());
				String resultCode = CodeGenUtil.getCodeGen(paramsMap);
				Gson gson = new Gson();
				Map<String,Object> map = gson.fromJson(resultCode, new TypeToken<Map<String,Object>>() {
				}.getType());
				if(Double.parseDouble(map.get("resCode")+"")==200){
					entity.setPaymentCode(map.get("data").toString());
				}
				entity.setAdminUserId(adminUserId);
				entity.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
				entity.setUpdateTime(new java.sql.Timestamp(System.currentTimeMillis()));
				Serializable otherId = this.tssPaymentService.saveEntity(entity);
				if(otherId == null) {
					ajr.setResCode(301);
					ajr.setResMsg("保存其它缴费信息失败!");
				}
				//缴费记录
				TssPayment tssPayment = tssPaymentService.get(otherId);
				historyId = tssPaymentHistoryService.saveHistory(tssPayment);
				if (historyId == null) {
					ajr.setResCode(301);
					ajr.setResMsg("保存操作历史信息失败!");
				}
				if(entity.getPaymentType() == 4){
					TssMealFee tssMealFee = new TssMealFee();
					Double amount = entity.getAmount();
					List<TssMealFee> destEntity = this.tssMealFeeService.findByProperty("stuId",entity.getStuId());
					if(destEntity.size() > 0){
						amount = amount + destEntity.get(0).getAmount();
						tssMealFee.setAmount(amount);
						Double surplusAmout = amount + destEntity.get(0).getSurplusAmout();
						tssMealFee.setSurplusAmout(surplusAmout);
						tssMealFee.setUpdateTime(new java.sql.Timestamp(System.currentTimeMillis()));
						BeanUtils.copyProperties(tssMealFee,destEntity.get(0),"id","stuId","dayMealFee","consumptionAmount","createTime");
						this.tssMealFeeService.updateTssMealFee(destEntity.get(0));
					} else {
						tssMealFee.setStuId(entity.getStuId());
						tssMealFee.setAmount(amount);
						tssMealFee.setSurplusAmout(amount);
						tssMealFee.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
						tssMealFee.setUpdateTime(new java.sql.Timestamp(System.currentTimeMillis()));

						Serializable tssMealFeenewId = this.tssMealFeeService.saveTssMealFee(tssMealFee);
						if (tssMealFeenewId == null) {
							ajr.setResCode(301);
							ajr.setResMsg("保存餐点费失败!");
						}
					}
				}

				//一次性物品费权责
				if(entity.getPaymentType() == 5) {
					HashMap<String, Object> map1 = new HashMap<>();
					map1.put("memberId", entity.getStuId());
					map1.put("paymentId", otherId);
					boolean d = tssRightStatisticService.saveOrUpdateTssRightStatisticService(null, map1, adminUserId,4,8,0, entity.getAmount());

					if (!d) {
						ajr.setResCode(301);
						ajr.setResMsg("保存一次性物品费权责失败!");
					}
				}
				List<TssAllocation> tssAllocations = tssAllocationService.findByEmpAdminUserId(entity.getEmpAdminUserId(),studentId);
				if(tssAllocations.size()<1){
					TssAllocation tssAllocation = new TssAllocation();
					tssAllocation.setStudentId(entity.getStuId());
					tssAllocation.setEmpAdminUserId(entity.getEmpAdminUserId());
					tssAllocation.setAdminUserId(adminUserId);
					tssAllocation.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
					Serializable save = tssAllocationService.save(tssAllocation);
				}
				//更新会员顾问
				this.tssStudentService.updateParameterById(ImmutableMap.of("empAdminUserId",entity.getEmpAdminUserId()),studentId);
			}
			//this.tssStudentService.updateParameterById(ImmutableMap.of("stuStatus",1),studentId);

		} catch (Exception e) {
			e.printStackTrace();
			ajr.setResCode(500);
			ajr.setResMsg("保存失败(" + e.getMessage() + ")!");
		}
		return ajr.jsonResponse(false);
	}
	
	/**
	 * 删除指定id的对象
	 * 
	 * @param id
	 *            需要被删除的对象id
	 * @return
	 */
	@ResponseBody
	@RequestLog(content = "删除属性" , save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "delete" , method = RequestMethod.GET)
	public String delete(@StringValidator(nullable = false) String id) {
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		try {
			ajr.setResMsg("删除成功!");
			if(StringUtils.isNotBlank(id)) {
				this.tssPaymentService.deleteEntityById(id);
			} else {
				ajr.setResMsg("删除失败!");
				ajr.setResCode(302);
			}
		} catch (Exception e) {
			e.printStackTrace();
			ajr.setResCode(500);
			ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
		}
		return ajr.jsonResponse(false);
	}
	
	/**
	 * 批量删除指定id的对象
	 * 
	 * @param ids
	 *            需要被删除的对象id组成的字符串
	 * @return
	 */
	@ResponseBody
	@RequestLog(content = "删除属性" , save = true)
	@Token(validateToken = false)
	@RequestMapping(value = "batchDelete" , method = RequestMethod.GET)
	public String batchDelete(@RegexpValidator(nullable = false , regexp = "^(\\w+,?)+\\w+$") String ids) {
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		try {
			ajr.setResMsg("删除成功!");
			if(StringUtils.isNotBlank(ids)) {
				boolean batchDelete = this.tssPaymentService.batchDelete(ids.split(","));
				if(!batchDelete) {
					ajr.setResMsg("删除失败!");
					ajr.setResCode(302);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			ajr.setResCode(500);
			ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
		}
		return ajr.jsonResponse(false);
	}

	/**
	 * 测试
	 * */

	@RequestMapping("/abc")
	@ResponseBody
	public void abc(HttpServletResponse response, String ids) throws Exception{
		System.out.print(ids);
		response.getWriter().print("true");
	}


	/**
	 * 财务管理>收支管理 导出
	 * 杨然
	 * 2017年11月9日19:15:37
	 * */
	@RequestLog(content = "导出", save = true)
	@Token(validateToken = false)
	@ResponseBody
	@RequestMapping("/exportExcle")
	public void exportExcle(Integer flag, String ids, ViewPaymentReturnPremium entity, HttpServletResponse response, HttpServletRequest request){
		String path = "jso/export_payment.json";
		String templateName = request.getParameter("templateName");
		List<ViewPaymentReturnPremium> paymentList = null;

		paymentList = iViewPaymentReturnPremiumService.getAllList();

		ExportUtil export = new ExportUtil();
		export.export(path,templateName, paymentList, request, response);

	}

	/**
	 * 财务管理>收支记录 导出
	 * 杨然
	 * 2017年11月10日09:30:37
	 * */
	@RequestLog(content = "导出", save = true)
	@Token(validateToken = false)
	@ResponseBody
	@RequestMapping("/exportExclePaymentDetails")
	public void exportExclePaymentDetails(Integer flag, String ids, ViewPaymentDetails entity, HttpServletResponse response, HttpServletRequest request){
		String path = "jso/export_paymentDetails.json";
		String templateName = request.getParameter("templateName");
		List<ViewPaymentDetails> paymentList = null;

		if(ids != ""){

			paymentList = viewPaymentDetailsService.findListByIds(Arrays.asList(ids.split(",")));

		} else{
			paymentList = viewPaymentDetailsService.getAllList();
		}

		ExportUtil export = new ExportUtil();
		export.export(path,templateName, paymentList, request, response);
	}


	/**
	 * 财务管理>缴费管理 导出
	 * 杨然
	 * 2017年11月10日09:56:40
	 * */
	/*@RequestLog(content = "导出", save = true)
	@Token(validateToken = false)
	@ResponseBody
	@RequestMapping("/exportExclePaymentList")
	public void exportExclePaymentList(Integer flag, String ids, ViewPaymentStudentPackage entity, HttpServletResponse response, HttpServletRequest request){
		String path = "jso/export_paymentList.json";
		String templateName = request.getParameter("templateName");
		List<ViewPaymentStudentPackage> paymentList = null;

		if(ids != ""){

			paymentList = iViewPaymentStudentPackageService.findListByIds(Arrays.asList(ids.split(",")));

		} else{
			paymentList = iViewPaymentStudentPackageService.getAllList();
		}
		System.out.println(paymentList);
		ExportUtil export = new ExportUtil();
		export.export(path,templateName, paymentList, request, response);
	}*/

}
